<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 基地详情
 *
 * @author      Eden
 * @datetime    2016/12/18 16:22
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Detail2_Model extends API_Model
{

    // 基地ID
    private $goodsId = 0;
    private $userId = 0;
    protected $width = 800;
    protected $height = 800;
    protected $userType = 0;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {
        $send['state'] = false;
        do {

            $this->userType = $this->getUserType(value($params, 'userId'));

            if (empty($params['goodsId'])) {
                $send['error'] = '产品不存在';
                break;
            }

            if (!empty($params['userId'])) {
                $this->userId = intval($params['userId']);
            }

            $this->goodsId = (int) $params['goodsId'];

            $res = $this->getGoodsDetail();
            if (!$res) {
                $send['error'] = $this->getError();
            } else {
                @statIncr('pv');
                $send['state'] = true;
                $send['data'] = $res;
            }
        }while(false);
        $this->output->send($send);
    }

    /**
     * 商品详情
     * @return bool
     */
    public function getGoodsDetail()
    {
        $db = clone($this->db);
        $q = $db->select('g.goodsName, g.description, g.baseId, bc.name as categoryName, b.name as baseName, g.thumb,
            g.recommendThumb, g.bannerThumb, g.streamId, g.content, g.pv, g.likes, g.liveUrl,
            g.stars, g.comments, g.price, g.minPrice, g.minPurPrice, g.maxPrice, g.maxPurPrice, g.stock, g.unit, g.expType, g.expAmount, g.expressWeight, g.created, g.sold, g.status')
            ->from('base_goods as g')
            ->join('base as b', 'b.id = g.baseId')
            ->join('base_category as bc', 'bc.id = g.categoryId')
            ->where('g.status = 1')
            ->where('g.id', $this->goodsId)
            ->get();
        $row = $q->row_array();

        if (empty($row)) {
            $this->setError('商品不存在');
            return false;
        }


        $rule = $this->_rule($this->goodsId);

        $thumb = !empty($row['bannerThumb']) ? $row['bannerThumb'] : $row['thumb'];

        $result = [];
        $result['goodsName'] = value($row, 'goodsName');
        $result['description'] = value($row, 'description');
        $result['rules'] = $rule;
        $result['goodsId'] = $this->goodsId;
        $result['baseId'] = intval($row['baseId']);
        $result['thumb'] = thumb($thumb, $this->width, $this->height);
        $result['thumbs'] = $this->_getThumbs();
        $result['pv'] = intval($row['pv']);
        $result['likes'] = intval($row['likes']);
        $result['stock'] = intval($row['stock']);
        $result['stars'] = intval($row['stars']);
        $result['minPrice'] = money_format('%i', $row['minPrice'] / 100);
        $result['maxPrice'] = money_format('%i', $row['maxPrice'] / 100);
        $result['created'] = formateTimeStamp($row['created']);
        $result['content'] = $this->_content($row['goodsName'], $row['content']);
        $result['isCollected'] = $this->checkCollected();
        $result['isLive'] = !empty($row['liveUrl']);
        $result['liveUrl'] = value($row, 'liveUrl');
        $result['saleCount'] = intval($row['sold']);
        $result['expType'] = intval(value($row, 'expType', 1));
        $result['expAmount'] = intval(value($row, 'expAmount', 0));

        $result['comments'] = array(
            'total' => intval($row['comments']),
            'data' => $this->_get2Comments()
        );
        $result['related'] = $this->_getRelatedGoods();

        return $result;
    }

    /**
     * 总销量
     * @param int $goodsId
     * @return mixed
     */
    public function _getSaleStock($goodsId = 0)
    {
        $db = clone ($this->db);
        $db->where('orderId', $goodsId);
        return $db->count_all_results('user_order_goods');
    }

    /**
     * 缩略图
     * @return array
     */
    private function _getThumbs()
    {
        $db = clone($this->db);
        $q = $db->get_where('base_goods_thumb', ['goods_id' => $this->goodsId]);
        $items = $q->result_array();
        $thumbs = [];
        foreach ($items as $item) {
            $thumbs[] = [
                'id' => $item['id'],
                'thumb' => thumb($item['thumb'], $this->width, $this->height)
            ];
        }
        return $thumbs;
    }

    /**
     * rule
     * @param $goodsID
     * @return mixed
     */
    private function _rule($goodsID)
    {
        $db = clone($this->db);
        $query = $db->where(['goods_id' => $goodsID])->order_by('id', 'ASC')->get('base_goods_rule');

        $rules = $query->result_array();
        if (!empty($rules)) foreach ($rules as &$rule) {
            $rule['id'] = intval($rule['id']);
            $rule['goods_id'] = intval($rule['goods_id']);
            $rule['oldPrice'] = money_format('%i', $rule['oldPrice'] / 100);
            $rule['salePrice'] = money_format('%i', $rule['salePrice'] / 100);
            $rule['purchaserPrice'] = money_format('%i', $rule['purchaserPrice'] / 100);
            $rule['stock'] = intval($rule['stock']);
            $rule['weight'] = doubleval($rule['weight']);
            unset($rule['expressWeight'], $rule['status']);
        }
        return $rules;
    }

    /**
     * 检查用户是否收藏
     * @return bool
     */
    private function checkCollected()
    {
        if (empty($this->userId)) {
            return false;
        }
        $db = clone($this->db);
        $q = $db->get_where('user_collect', array('userId' => $this->userId, 'goodsId' => $this->goodsId));
        if ($q->row_array()) {
            return true;
        }
        return false;
    }

    /**
     * 相关产品
     * @return array
     */
    private function _getRelatedGoods()
    {
        $detail= array(
            'total' => 0,
            'data' => []
        );
        $db = clone($this->db);
        $q = $db->select('id, goodsName, thumb, liveUrl, thumbWidth, thumbHeight, streamId, price, minPrice, minPurPrice, created')
            ->from('base_goods')
            ->order_by('pv', 'DESC')
            ->limit(8)
            ->where(array('status' => 1))
            ->where('stock > 0')
            ->get();
        $rows = $q->result_array();
        if (empty($rows)){
            return $detail;
        }

        $results = $this->_doAfterSelectGoods($rows);
        $detail['total'] = count($results);
        $detail['data'] = $results;
        return $detail;
    }

    /**
     * 处理返回结果
     * @param array $goods
     * @return array
     */
    private function _doAfterSelectGoods($goods = array())
    {
        $results = $goodsIds = [];
        foreach($goods as $item) {
            $goodsIds[] = $item['id'];
            $wh = $this->countWidthHeight($item['thumbWidth'], $item['thumbHeight']);
            // $rule = $this->_rule($item['id']);
            $price = $this->userType == 1 ? $item['minPurPrice'] : $item['minPrice'];
            $results[] = array(
                'goodsId' => intval($item['id']),
                'goodsName' => value($item, 'goodsName'),
                'thumb' => thumb($item['thumb'], $wh['width'], $wh['height']),
                'width' => intval($wh['width']),
                'height' => intval($wh['height']),
                'price' => money_format('%i', $price / 100),
                'created' => formateTimeStamp($item['created']),
                'isLive' => !empty($item['liveUrl']),
                'isCollected' => false,
                'isAddToCar' => false,
                'liveUrl' => value($item, 'liveUrl')
            );
        }

        if (!empty($this->userId)) {
            $collects = $this->_getCollects($this->userId, $goodsIds);
            $cars = $this->_getCars($this->userId, $goodsIds);
            foreach ($results as &$item) {
                $id = $item['goodsId'];
                if (!empty($collects) && in_array($id, $collects)) {
                    $item['isCollected'] = true;
                }

                if (!empty($cars) && in_array($id, $cars)) {
                    $item['isAddToCar'] = true;
                }
            }
        }

        return $results;
    }

    /**
     * 获取两条最新的留言
     * @return array
     */
    private function _get2Comments()
    {
        $db = clone($this->db);
        $q = $db->select('c.content, c.created, u.nickName, up.avatar')
            ->where(array('c.status' => 1, 'c.goodsId' => $this->goodsId))
            ->limit(2)
            ->join('user as u', 'u.id = c.userId')
            ->from('base_goods_comments as c')
            ->order_by('c.created', 'DESC')
            ->join('user_profile as up', 'up.userId = c.userId')
            ->get();

        $rows = $q->result_array();
        if (empty($rows)) {
            return [];
        }

        foreach($rows as &$item) {
            $item['avatar'] = thumb($item['avatar'], 100, 100);
            $item['created'] = formateTimeStamp($item['created']);
        }

        return $rows;
    }

    /**
     * 渲染Content
     * @param string $title
     * @param string $content
     * @return mixed
     */
    private function _content($title = '', $content = '')
    {
        return $this->load->view('app/goods/detail.html', array(
            'title' => $title,
            'content' => $content
        ), true);
    }

}
